#!/bin/bash

# 设置颜色
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

# 加载环境变量
if [ -f .env ]; then
    source .env
else
    echo -e "${RED}.env file not found${NC}"
    exit 1
fi

# 检查环境变量
if [ -z "$MONGODB_URI" ]; then
    echo -e "${RED}MONGODB_URI is not set${NC}"
    exit 1
fi

echo -e "${GREEN}Starting database seeding...${NC}"

# 检查数据库连接
echo -e "${YELLOW}Checking database connection...${NC}"
if ! mongosh "$MONGODB_URI" --eval "db.stats()" > /dev/null 2>&1; then
    echo -e "${RED}Could not connect to database${NC}"
    exit 1
fi

# 执行数据库种子脚本
echo -e "${YELLOW}Running seed script...${NC}"
mongosh "$MONGODB_URI" scripts/seed-data.js

# 检查执行结果
if [ $? -eq 0 ]; then
    echo -e "${GREEN}Database seeding completed successfully!${NC}"
    
    # 显示数据统计
    echo -e "${YELLOW}Database statistics:${NC}"
    mongosh "$MONGODB_URI" --eval "
        print('Users count: ' + db.users.countDocuments())
        print('Questions count: ' + db.questions.countDocuments())
        print('Evaluations count: ' + db.evaluations.countDocuments())
        print('Audit logs count: ' + db.auditLogs.countDocuments())
    "
else
    echo -e "${RED}Database seeding failed${NC}"
    exit 1
fi

# 设置文件权限
echo -e "${YELLOW}Setting file permissions...${NC}"
chmod +x scripts/*.sh

echo -e "${GREEN}All done!${NC}"
